import { shop } from '@/types/shop'
import { usePromise } from '@/hooks/core/usePromise'
import { cloneDeep } from 'lodash-es'

export function useStops() {
  /**
   * 添加分类时的自动分组
   */
  // sections的类型怎么写
  function addTypesToSections(sections: any) {
    const tmp: addTypesToSectionsItem = { index1: [], index2: [] }
    sections.forEach((numberArr: number[]) => {
      if (numberArr.length >= 2) {
        if (numberArr[0] === 1) {
          tmp.index1.push(numberArr[1])
        } else if (numberArr[0] === 2) {
          tmp.index2.push(numberArr[1])
        }
      }
    })
    return tmp
  }

  function shopsStatusDic() {
    return [
      { label: '下架', value: 0 },
      { label: '上架', value: 1 },
      { label: '已售完', value: 2 },
    ]
  }

  function salesStatusDic() {
    return [
      { label: '隐藏', value: 0 },
      { label: '显示', value: 1 },
    ]
  }
  return {
    addTypesToSections,
    salesStatusDic,
    shopsStatusDic,
  }
}

interface addTypesToSectionsItem {
  index1: number[]
  index2: number[]
}

// 通用排序 传入search
// 通过id或者index确定是否分页请求下/上一页
/**
 * @param search
 * @param actionItem
 * @param isUp 是升是降
 * @param nowTableDatas 当前表数据
 * @param sortApiFunc 排序api
 * @param tableDataApi 刷新列表的api
 * @param callback (res, errMsg)
 */
export async function useTableSort<T = any>(
  search: any,
  actionItem: shop,
  isUp: boolean,
  nowTableDatas: shop[],
  sortApiFunc: Function,
  tableDataApi: Function,
  callback: Function
) {
  const { to } = usePromise()
  let sortIndex = null
  nowTableDatas.forEach((value, index) => {
    if (actionItem.id === value.id) {
      sortIndex = index
    }
  })
  // 如果分页时处于上级或者下级页面 自动请求分页数据
  if (sortIndex === nowTableDatas.length - 1 && !isUp) {
    const searchClone = cloneDeep(search)
    searchClone.pageIndex += 1
    await getSortApi(searchClone)
  } else if (sortIndex === 0 && isUp) {
    const searchClone = cloneDeep(search)
    searchClone.pageIndex -= 1
    await getSortApi(searchClone)
  } else {
    // 如果不是边界，根据isUp去增减
    if (sortIndex || sortIndex === 0) {
      const targetItem: shop =
        nowTableDatas[isUp ? sortIndex - 1 : sortIndex + 1]
      postSortApiFunc(targetItem)
    }
  }

  async function getSortApi(searchClone: any) {
    const [err, res] = await to(tableDataApi(searchClone))
    if (!err) {
      if (!res.data || res?.data.length === 0) {
        callback(null, '已是第一或最后一页')
        return
      }
      const targetItem = isUp ? res.data[res.data.length - 1] : res.data[0]

      postSortApiFunc(targetItem)
    }
  }

  async function postSortApiFunc(targetItem: shop) {
    if (!targetItem) callback(null, '切换排序失败')
    const [err, sortRes] = await to(
      sortApiFunc({ tid: targetItem.id, oid: actionItem.id })
    )
    if (!err) {
      callback(sortRes, '切换排序成功')
    } else {
      callback(null, '切换排序失败')
    }
  }
}
